package com.ctgu.admin.system.controller;

import com.ctgu.common.constant.AdminConst;
import com.ctgu.common.enums.ResultEnum;
import com.ctgu.common.exception.ResultException;
import com.ctgu.common.utils.EntityBeanUtil;
import com.ctgu.component.shiro.ShiroUtil;
import com.ctgu.modules.system.domain.Dept;
import com.ctgu.modules.system.domain.User;

import com.ctgu.modules.system.service.DeptService;
import com.ctgu.modules.system.service.RoleService;
import com.ctgu.modules.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


@Controller
public class RegisterController {
    @Autowired
    private UserService userService;

    @Autowired
    private DeptService deptService;




    /**
     * 用户注册界面
     */
    @PostMapping("/userRegister")
    public String userRegister(@RequestParam("username")String userName,
                           @RequestParam("nickname")String nickName,
                           @RequestParam("password")String password,
                           @RequestParam("email")String email,
                           @RequestParam("gender")Byte gender,
                           Model model) {
        System.out.println("准备注册:"+userName);
        User user = new User();
        user.setUsername(userName);
        user.setPassword(password);
        user.setNickname(nickName);
        user.setEmail(email);
        user.setSex(gender);
        Dept dept = new Dept();
        dept = deptService.getById(6L);
        user.setDept(dept);
        // 验证数据是否合格
        if (user.getId() == null) {

            // 判断密码是否为空
            if (password.isEmpty() || "".equals(password.trim())) {
                System.out.println("密码为空!");
                model.addAttribute("msg",new ResultException(ResultEnum.USER_PWD_NULL));
                return "/register";
            }


            // 对密码进行加密
            String salt = ShiroUtil.getRandomSalt();
            String encrypt = ShiroUtil.encrypt(user.getPassword(), salt);
            user.setPassword(encrypt);
            user.setSalt(salt);
        }

        // 判断用户名是否重复
        if (userService.repeatByUsername(user)) {
            System.out.println("重复姓名!"+userName);
            model.addAttribute("msg",new ResultException(ResultEnum.USER_EXIST));
            return "/register";
        }

        // 保存数据
        userService.save(user);
        //System.out.println("注册成功");
        model.addAttribute("operation","注册");
        model.addAttribute("msg","注册成功");
        return "/success";
    }

}

